<template>
	<view class="oa-content">
		<!-- 顶部自定义导航 -->
		<tn-nav-bar fixed customBack :bottomShadow="false" backgroundColor="#FFFFFF">
			<view slot="back" class='tn-custom-nav-bar__back' @click="goBack">
				<text class='icon tn-icon-left-arrow'></text>
			</view>
			<view class="tn-flex tn-flex-col-center tn-flex-row-center ">
				<text class="tn-text-bold tn-text-xl tn-color-black">客户详情</text>
			</view>
		</tn-nav-bar>

		<view class="" :style="{paddingTop: vuex_custom_bar_height + 30 + 'px'}" style="padding-bottom: 240rpx;">
			
			<!-- 客户基本信息卡片 -->
			<view class="customer-info-card tn-margin">
				<view class="card-header tn-flex tn-flex-row-between tn-flex-col-center tn-padding">
					<text class="tn-text-bold tn-text-xl tn-color-black">{{customerInfo.name}}</text>
					<view class="status-tags">
						<tn-tag v-if="customerInfo.lockStatus === '1'" backgroundColor="#FF6B6B" fontColor="#FFFFFF" size="sm">已锁定</tn-tag>
						<tn-tag v-if="customerInfo.dealStatus === '1'" backgroundColor="#00C8B0" fontColor="#FFFFFF" size="sm">已成交</tn-tag>
					</view>
				</view>
				
				<view class="card-content tn-padding">
					<!-- 客户来源 -->
					<view class="info-row tn-flex tn-flex-row-between tn-padding-bottom-sm">
						<text class="label tn-color-gray">客户来源</text>
						<text class="value tn-color-black">{{getSourceLabel(customerInfo.source)}}</text>
					</view>
					
					<!-- 客户级别 -->
					<view class="info-row tn-flex tn-flex-row-between tn-padding-bottom-sm">
						<text class="label tn-color-gray">客户级别</text>
						<text class="value tn-color-black">{{getLevelLabel(customerInfo.level)}}</text>
					</view>
					
					<!-- 客户行业 -->
					<view class="info-row tn-flex tn-flex-row-between tn-padding-bottom-sm">
						<text class="label tn-color-gray">客户行业</text>
						<text class="value tn-color-black">{{getIndustryLabel(customerInfo.industryId)}}</text>
					</view>
					
					<!-- 联系方式 -->
					<view class="info-row tn-flex tn-flex-row-between tn-padding-bottom-sm">
						<text class="label tn-color-gray">手机号码</text>
						<text class="value tn-color-black">{{customerInfo.mobile || '未填写'}}</text>
					</view>
					
					<view class="info-row tn-flex tn-flex-row-between tn-padding-bottom-sm">
						<text class="label tn-color-gray">固定电话</text>
						<text class="value tn-color-black">{{customerInfo.telephone || '未填写'}}</text>
					</view>
					
					<view class="info-row tn-flex tn-flex-row-between tn-padding-bottom-sm">
						<text class="label tn-color-gray">邮箱地址</text>
						<text class="value tn-color-black">{{customerInfo.email || '未填写'}}</text>
					</view>
					
					<!-- 地址信息 -->
					<view class="info-row tn-flex tn-flex-row-between tn-padding-bottom-sm">
						<text class="label tn-color-gray">详细地址</text>
						<text class="value tn-color-black">{{customerInfo.detailAddress || '未填写'}}</text>
					</view>
					
					<!-- 下次联系时间 -->
					<view class="info-row tn-flex tn-flex-row-between tn-padding-bottom-sm">
						<text class="label tn-color-gray">下次联系时间</text>
						<text class="value tn-color-black">{{formatDate(customerInfo.contactNextTime) || '未设置'}}</text>
					</view>
					
					<!-- 备注信息 -->
					<view class="info-row tn-flex tn-flex-row-between tn-padding-bottom-sm" v-if="customerInfo.remark">
						<text class="label tn-color-gray">备注信息</text>
						<text class="value tn-color-black">{{customerInfo.remark}}</text>
					</view>
				</view>
			</view>

			<!-- 操作按钮区域 -->
			<view class="action-buttons tn-margin">
				<view class="tn-flex tn-flex-row-between tn-padding-bottom">
					<tn-button backgroundColor="#00C8B0" fontColor="#FFFFFF" width="48%" @click="editCustomer">
						<text class="tn-icon-edit tn-padding-right-xs"></text>
						编辑客户
					</tn-button>
					<tn-button backgroundColor="#4B98FE" fontColor="#FFFFFF" width="48%" @click="makeCall">
						<text class="tn-icon-phone tn-padding-right-xs"></text>
						拨打电话
					</tn-button>
				</view>
				
				<view class="tn-flex tn-flex-row-between tn-padding-bottom">
					<tn-button backgroundColor="#FF9500" fontColor="#FFFFFF" width="48%" @click="addFollowUpRecord">
						<text class="tn-icon-edit tn-padding-right-xs"></text>
						添加跟进
					</tn-button>
					<tn-button backgroundColor="#FF6B6B" fontColor="#FFFFFF" width="48%" @click="deleteCustomer">
						<text class="tn-icon-delete tn-padding-right-xs"></text>
						删除客户
					</tn-button>
				</view>
			</view>

			<!-- 联系记录 -->
			<view class="contact-records tn-margin">
				<view class="section-title tn-padding-bottom">
					<text class="tn-text-bold tn-text-lg tn-color-black">联系记录</text>
				</view>
				
				<view class="record-list">
					<view v-if="contactRecords.length === 0" class="empty-state tn-text-center tn-padding">
						<text class="tn-color-gray">暂无联系记录</text>
					</view>
					
					<view v-for="(record, index) in contactRecords" :key="index" class="record-item">
						<!-- 记录头部 -->
						<view class="record-header">
							<view class="record-type-badge">
								<view class="type-icon" :class="getTypeIconClass(record.type)"></view>
								<text class="type-text">{{getFollowUpTypeLabel(record.type)}}</text>
							</view>
							<text class="record-time">{{formatDate(record.createTime)}}</text>
						</view>
						
						<!-- 记录内容 -->
						<view class="record-content">
							<text class="content-text">{{record.content}}</text>
						</view>
						
						<!-- 记录详情 -->
						<view class="record-details" v-if="hasRecordDetails(record)">
							<view class="details-grid">
								<view class="detail-item" v-if="record.contacts && record.contacts.length > 0">
									<view class="detail-icon">
										<text class="icon tn-icon-user"></text>
									</view>
									<view class="detail-info">
										<text class="detail-label">相关联系人</text>
										<text class="detail-value">{{getContactNames(record.contacts)}}</text>
									</view>
								</view>
								
								<view class="detail-item" v-if="record.businesses && record.businesses.length > 0">
									<view class="detail-icon">
										<text class="icon tn-icon-briefcase"></text>
									</view>
									<view class="detail-info">
										<text class="detail-label">相关商机</text>
										<text class="detail-value">{{getBusinessNames(record.businesses)}}</text>
									</view>
								</view>
								
								<view class="detail-item" v-if="record.nextTime">
									<view class="detail-icon">
										<text class="icon tn-icon-calendar"></text>
									</view>
									<view class="detail-info">
										<text class="detail-label">下次跟进</text>
										<text class="detail-value">{{formatDate(record.nextTime)}}</text>
									</view>
								</view>
								
								<view class="detail-item">
									<view class="detail-icon">
										<text class="icon tn-icon-account"></text>
									</view>
									<view class="detail-info">
										<text class="detail-label">创建人</text>
										<text class="detail-value">{{record.creatorName}}</text>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>

		</view>
	</view>
</template>

<script>
	import template_page_mixin from '@/libs/mixin/template_page_mixin.js'
	import {
		getCustomerDetail,
		deleteCustomer
	} from '@/api/crm/customer.js'
	
	export default {
		name: 'CustomerDetail',
		mixins: [template_page_mixin],

		data() {
			return {
				customerId: null,
				customerInfo: {},
				contactRecords: []
			}
		},
		
		onLoad(options) {
			if (options.id) {
				this.customerId = options.id
				this.loadCustomerDetail()
			}
		},
		
		methods: {
			// 加载客户详情
			async loadCustomerDetail() {
				try {
					uni.showLoading({
						title: '加载中...'
					})
					
					const response = await this.api.get(`/crm/customer/get?id=${this.customerId}`)
					if (response) {
						this.customerInfo = response
						this.loadContactRecords()
					}
				} catch (error) {
					console.error('加载客户详情失败:', error)
					uni.showToast({
						title: '加载失败，请重试',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			},
			
			// 加载联系记录
			async loadContactRecords() {
				try {
					const response = await this.api.get(`/crm/follow-up-record/page?pageNo=1&pageSize=10&bizType=2&bizId=${this.customerId}`)
					if (response && response.list) {
						this.contactRecords = response.list
					}
				} catch (error) {
					console.error('加载联系记录失败:', error)
				}
			},
			
			// 获取客户来源标签
			getSourceLabel(source) {
				if (!source || !this.DICT.crm_customer_source) return '未知'
				const sourceItem = this.DICT.crm_customer_source.find(item => item.value === source)
				return sourceItem ? sourceItem.label : '未知'
			},
			
			// 获取客户级别标签
			getLevelLabel(level) {
				if (!level || !this.DICT.crm_customer_level) return '未知'
				const levelItem = this.DICT.crm_customer_level.find(item => item.value === level)
				return levelItem ? levelItem.label : '未知'
			},
			
			// 获取客户行业标签
			getIndustryLabel(industryId) {
				if (!industryId || !this.DICT.crm_customer_industry) return '未知'
				const industryItem = this.DICT.crm_customer_industry.find(item => item.value === industryId)
				return industryItem ? industryItem.label : '未知'
			},
			
			// 获取跟进记录类型标签
			getFollowUpTypeLabel(type) {
				const typeMap = {
					1: '电话跟进',
					2: '邮件跟进',
					3: '上门拜访',
					4: '其他'
				}
				return typeMap[type] || '未知类型'
			},
			
			// 获取联系人名称列表
			getContactNames(contacts) {
				if (!contacts || contacts.length === 0) return '无'
				return contacts.map(contact => contact.name).join('、')
			},
			
			// 获取商机名称列表
			getBusinessNames(businesses) {
				if (!businesses || businesses.length === 0) return '无'
				return businesses.map(business => business.name).join('、')
			},
			
			// 获取类型图标样式类
			getTypeIconClass(type) {
				const iconMap = {
					1: 'phone-icon',
					2: 'mail-icon', 
					3: 'visit-icon',
					4: 'other-icon'
				}
				return iconMap[type] || 'other-icon'
			},
			
			// 判断是否有记录详情
			hasRecordDetails(record) {
				return (record.contacts && record.contacts.length > 0) ||
					   (record.businesses && record.businesses.length > 0) ||
					   record.nextTime ||
					   record.creatorName
			},
			
			// 格式化日期
			formatDate(timestamp) {
				if (!timestamp) return ''
				const date = new Date(timestamp)
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
			},
			
			// 编辑客户
			editCustomer() {
				uni.navigateTo({
					url: `/crm/customer/edit?id=${this.customerId}`
				})
			},
			
			// 拨打电话
			makeCall() {
				const phone = this.customerInfo.mobile || this.customerInfo.telephone
				if (!phone) {
					uni.showToast({
						title: '该客户暂无联系方式',
						icon: 'none'
					})
					return
				}
				
				uni.makePhoneCall({
					phoneNumber: phone,
					success: () => {
						console.log('拨打电话成功')
					},
					fail: (err) => {
						console.error('拨打电话失败:', err)
					}
				})
			},
			
			// 添加跟进记录
			addFollowUpRecord() {
				uni.navigateTo({
					url: `/crm/follow-up-record/add?customerId=${this.customerId}`
				})
			},

			// 发送消息
			sendMessage() {
				uni.showToast({
					title: '功能开发中',
					icon: 'none'
				})
			},
			
			// 删除客户
			deleteCustomer() {
				uni.showModal({
					title: '确认删除',
					content: '确定要删除该客户吗？删除后无法恢复。',
					confirmColor: '#FF6B6B',
					success: async (res) => {
						if (res.confirm) {
							try {
								uni.showLoading({
									title: '删除中...'
								})
								
								const response = await this.api.delete(`/crm/customer/delete?id=${this.customerId}`)
								if (response) {
									uni.showToast({
										title: '删除成功',
										icon: 'success'
									})
									
									setTimeout(() => {
										uni.navigateBack()
									}, 1500)
								}
							} catch (error) {
								console.error('删除客户失败:', error)
								uni.showToast({
									title: '删除失败，请重试',
									icon: 'none'
								})
							} finally {
								uni.hideLoading()
							}
						}
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	/* 胶囊*/
	.tn-custom-nav-bar__back {
		width: 60%;
		height: 100%;
		position: relative;
		display: flex;
		justify-content: space-evenly;
		align-items: center;
		box-sizing: border-box;
		background-color: rgba(0, 0, 0, 0.15);
		border-radius: 1000rpx;
		border: 1rpx solid rgba(255, 255, 255, 0.5);
		color: #FFFFFF;
		font-size: 32rpx;

		.icon {
			display: block;
			flex: 1;
			margin: auto;
			text-align: center;
		}
	}

	.oa-content {
		max-width: 640px;
		margin: 0 auto;
		min-height: 100vh;
		padding-bottom: 60rpx;
		padding-bottom: calc(80rpx + env(safe-area-inset-bottom) / 2);
		padding-bottom: calc(80rpx + constant(safe-area-inset-bottom));
	}

	/* 客户信息卡片 */
	.customer-info-card {
		background-color: #FFFFFF;
		border-radius: 20rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
		
		.card-header {
			border-bottom: 1rpx solid #F8F9FB;
			
			.status-tags {
				.tn-tag {
					margin-left: 10rpx;
				}
			}
		}
		
		.card-content {
			.info-row {
				.label {
					font-size: 28rpx;
					min-width: 160rpx;
				}
				
				.value {
					font-size: 28rpx;
					text-align: right;
					flex: 1;
					margin-left: 20rpx;
				}
			}
		}
	}

	/* 操作按钮区域 */
	.action-buttons {
		background-color: #FFFFFF;
		border-radius: 20rpx;
		padding: 30rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
	}

	/* 联系记录 */
	.contact-records {
		background-color: #FFFFFF;
		border-radius: 20rpx;
		padding: 30rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
		
		.section-title {
			border-bottom: 1rpx solid #F8F9FB;
			margin-bottom: 30rpx;
		}
		
		.record-item {
			background: linear-gradient(135deg, #FFFFFF 0%, #F8F9FB 100%);
			border-radius: 16rpx;
			padding: 24rpx;
			margin-bottom: 20rpx;
			border: 1rpx solid #E8ECF0;
			box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
			transition: all 0.3s ease;
			
			&:hover {
				transform: translateY(-2rpx);
				box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
			}
			
			.record-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 16rpx;
				
				.record-type-badge {
					display: flex;
					align-items: center;
					background: linear-gradient(135deg, #4B98FE 0%, #6BB6FF 100%);
					padding: 8rpx 16rpx;
					border-radius: 20rpx;
					
					.type-icon {
						width: 24rpx;
						height: 24rpx;
						margin-right: 8rpx;
						border-radius: 50%;
						
						&.phone-icon {
							background: linear-gradient(135deg, #00C8B0 0%, #00E6C7 100%);
						}
						
						&.mail-icon {
							background: linear-gradient(135deg, #FF9500 0%, #FFB74D 100%);
						}
						
						&.visit-icon {
							background: linear-gradient(135deg, #FF6B6B 0%, #FF8A80 100%);
						}
						
						&.other-icon {
							background: linear-gradient(135deg, #9C27B0 0%, #BA68C8 100%);
						}
					}
					
					.type-text {
						color: #FFFFFF;
						font-size: 24rpx;
						font-weight: 600;
					}
				}
				
				.record-time {
					color: #8E8E93;
					font-size: 22rpx;
					background-color: #F2F2F7;
					padding: 6rpx 12rpx;
					border-radius: 12rpx;
				}
			}
			
			.record-content {
				margin-bottom: 20rpx;
				
				.content-text {
					color: #1C1C1E;
					font-size: 28rpx;
					line-height: 1.6;
					font-weight: 500;
				}
			}
			
			.record-details {
				background: linear-gradient(135deg, #F8F9FB 0%, #FFFFFF 100%);
				border-radius: 12rpx;
				padding: 20rpx;
				border: 1rpx solid #E8ECF0;
				
				.details-grid {
					display: grid;
					grid-template-columns: 1fr 1fr;
					gap: 16rpx;
					
					.detail-item {
						display: flex;
						align-items: center;
						padding: 12rpx;
						background-color: #FFFFFF;
						border-radius: 8rpx;
						border: 1rpx solid #F0F0F0;
						
						.detail-icon {
							width: 32rpx;
							height: 32rpx;
							background: linear-gradient(135deg, #4B98FE 0%, #6BB6FF 100%);
							border-radius: 50%;
							display: flex;
							align-items: center;
							justify-content: center;
							margin-right: 12rpx;
							
							.icon {
								color: #FFFFFF;
								font-size: 18rpx;
							}
						}
						
						.detail-info {
							flex: 1;
							
							.detail-label {
								display: block;
								color: #8E8E93;
								font-size: 20rpx;
								margin-bottom: 4rpx;
							}
							
							.detail-value {
								display: block;
								color: #1C1C1E;
								font-size: 22rpx;
								font-weight: 500;
								line-height: 1.3;
							}
						}
					}
				}
			}
		}
		
		.empty-state {
			padding: 80rpx 0;
			text-align: center;
			
			text {
				color: #8E8E93;
				font-size: 28rpx;
			}
		}
	}

	/* 间隔线 */
	.tn-strip-bottom-min {
		width: 100%;
		border-bottom: 1rpx solid #F8F9FB;
	}
</style>